package givenchy

class TaskGroup {

	String name = ""; // 站点名称
	String description // 站点描述
	Integer mask = 0 // 预留字段,区分任务组的工作内容
	Date last = new Date();
	User person
	static hasMany = [tasks: Task]


    Integer requireOfIP = 0 // 对ip质量的要求
	String hourRate = '' //时间分配 字符串以','号分隔
	Boolean isAd = false //是否是需要点击广告的task
	
    Integer total = 0; // 总流量计算用的每小时的量 
    Integer dayOfHour = 0;//当前统计的小时数

    static transients = ['dayOfHour' , 'total']

 
    static constraints = {
        name(blank:false)
        description()
    }

    static mapping = {
        tasks lazy:false
        //person lazy:false
    }

    String toString(){
        "${person.username}:${name}:${requireOfIP}:${tasks?.size()}"
    }

    String hourRateToString(){
        def result = ''
        
        hourRate.split(",").eachWithIndex{ it,i ->
            result += i+ ":" + it + "\t"; 
        } 
        return result
    }
      String buildHourRate(sourceRate){
        
        if (sourceRate) {
            if (sourceRate in String[]) {
                hourRate = sourceRate.join(',')
            }
        } 
    }

    String checkTask(int ipbest){
        
        log.info("TaskGroup.checkTask: ${rateMatch()}")
        if (rateMatch()) {
              if (requireOfIP <= ipbest) { // 验证ip质量 
                  return selectTasks()
              }
        }
    }

     // 验证否已经超过时间限制
    boolean rateMatch(){

        Calendar   calendar   =   Calendar.getInstance();
        def int hour = calendar.get(Calendar.HOUR_OF_DAY)
        def int minute = calendar.get(Calendar.MINUTE)
 
        def String[] rate = hourRate.split(',')
        if (dayOfHour != hour) {// 新的小时，清零计数器
            total = 0 
            dayOfHour == hour
        }

        def int eachhour = 0
        def boolean  pass = true

        if (rate) {
            rate.each{
                it = Integer.parseInt(it)
                if (eachhour == hour && it != 0) { 
                    
                    if ( it <= total) {
                        pass = false
                    }
                    log.info("rateMatch [(60 / it.rate)*total > minute]  = ${(60 / it.rate)*total} / ${minute}")
                    if ((60 / it)*total > minute) {
                        pass = false
                    }
                }
                eachhour++
            }
        }

        return pass
    }

 
    String selectTasks(){
        //  验证随机命中
        def result = ""

        if (tasks && !tasks.isEmpty()) {
            
            def seek = (int)(Math.random() * tasks?.seek.sum())
            def tasks_count=0;
            def f = true;

            // println seek + "///"
            tasks.each{ v  ->
                log.info "ever task action : "+ v.actions
                tasks_count += v.seek;
                if (tasks_count > seek && f && v.available && v.actions != '') { //随即命中，之前没有命中，可用，脚本不空
                    
                        result = v.buildScript()
                        f = false
                        total++
 
                }
            } 
        }
        return  result
    }
}
